import os
import configparser, zipfile, shutil
from src.globle import *
import glob

def download_file(download_flag,file_formit):
    download_tmp = f"/tmp/{download_flag}/"
    os.makedirs(download_tmp, exist_ok=True)
    config = configparser.ConfigParser()
    script_dir = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(script_dir, 'config_link.ini')
    config.read(file_path)

    if file_formit in ["act_zip", "deb_zip"]:
        download_tmp_file = f"{download_tmp}{download_flag}.zip"
    elif file_formit == "deb":
        download_tmp_file = f"{download_tmp}{download_flag}.deb"
        
    try:
        downzip_link = config.get(download_flag, sys_str)
    except configparser.NoOptionError:
        print("暂不支持")
        exit(1)
    if os.system(f"wget --no-check-certificate -O {download_tmp_file} {downzip_link}") != 0:
        print(f"{COLOR_RED}下载文件失败..{COLOR_NONE}")
        exit(1)

    os.chdir(download_tmp)
    if file_formit in ["act_zip", "deb_zip"]:
        with zipfile.ZipFile(download_tmp_file, 'r') as zip_ref:
            zip_ref.extractall('.')
        if file_formit == "deb_zip":
            for file in glob.glob("*.deb"):
                subprocess.run(["sudo", "chmod", "777", file], check=True)
            for file in glob.glob("*.deb"):
                subprocess.run(["sudo", "dpkg", "-i", file], check=True)
                subprocess.run(["sudo", "dpkg", "-i", file], check=True)
            get_pause
        elif file_formit == "act_zip":
            subprocess.run(["sudo", "cp", f"{download_tmp}/.kyinfo", "/etc/"], check=True)
            subprocess.run(["sudo", "cp", f"{download_tmp}/LICENSE", "/etc/"], check=True)
            print("应该是修改完了，关闭之前的激活页面，重新打开激活页面激活一下吧。")
            get_pause
        else:
            print("暂不支持")
            exit(1)
    elif file_formit == "deb":
        for file in glob.glob("*.deb"):
            subprocess.run(["sudo", "chmod", "777", file], check=True)
        for file in glob.glob("*.deb"):
            subprocess.run(["sudo", "dpkg", "-i", file], check=True)
        get_pause
    